import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_upgrade/flutter_app_upgrade.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/utils/log_util.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/view/mine/view_guide.dart';
import 'package:flutter_chip/widget/RouteSlide.dart';
import 'package:fsuper/fsuper.dart';

class AboutPage extends StatefulWidget {
  @override
  _AboutPageState createState() => _AboutPageState();
}

class _AboutPageState extends State<AboutPage> {
  bool isUpdate = false;
  String newVersion;
  String apkUrl;

  @override
  void initState() {
    super.initState();
    _updateVersion(true);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Theme.of(context).canvasColor,
      ),
      body: Column(
        children: <Widget>[
          _logoWidget(),
          _appNameWidget(),
          _versionWidget(),
          SizedBox(height: 30),
          _dividerWidget(),
          _funcWidget(),
          _dividerWidget(),
          _updateWidget(),
          _dividerWidget(),
          Expanded(child: Container(), flex: 1),
//          FSuper(
//            width: double.infinity,
//            height: 24,
//            text: "App隐私协议",
//            textAlignment: Alignment.center,
//            textColor: Theme.of(context).accentColor,
//            textSize: 12,
//            margin: EdgeInsets.only(bottom: 10),
//            onClick: () {
//              Navigator.of(context).push(
//                MaterialPageRoute(builder: (_) {
//                  return WebInfoPage("APP隐私协议", Api.BASE_URL + "/privacy.html",
//                      type: "web");
//                }),
//              );
//            },
//          ),
//          FSuper(
//            width: double.infinity,
//            height: 24,
//            text: "Copyright@陕西极客数据科技有限公司",
//            textAlignment: Alignment.center,
//            textColor: Color(0xffBBBBBB),
//            textSize: 12,
//            margin: EdgeInsets.only(bottom: 10),
//          ),
        ],
      ),
    );
  }

  ///LOGO显示
  Widget _logoWidget() {
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.only(top: 30),
      width: MediaQuery.of(context).size.width,
      child: Image.asset(
        Comm.IMG_APP_LOGO,
        width: 72,
        height: 72,
        fit: BoxFit.cover,
      ),
    );
  }

  ///app名称
  Widget _appNameWidget() {
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.only(top: 10),
      width: MediaQuery.of(context).size.width,
      child: Text(
        Comm.appName,
        style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
      ),
    );
  }

  ///当前版本号
  Widget _versionWidget() {
    return Container(
      alignment: Alignment.center,
      width: MediaQuery.of(context).size.width,
      child: Text(
        "V${Comm.versionName}",
        style: TextStyle(fontSize: 18, fontWeight: FontWeight.w300),
      ),
    );
  }

  ///功能介绍
  Widget _funcWidget() {
    return FSuper(
      width: double.infinity,
      height: 54,
      text: "功能介绍",
      textSize: 16,
      textAlignment: Alignment.centerLeft,
      padding: EdgeInsets.only(left: 20, right: 20),
      child1: Image.asset(Comm.IMG_ARROW_RIGHT, width: 18, height: 18),
      child1Alignment: Alignment.centerRight,
      child1Margin: EdgeInsets.only(right: 20),
      onClick: () {
        Navigator.of(context).push(RouteSlide(GuidePage()));
      },
    );
  }

  ///检查更新
  Widget _updateWidget() {
    return FSuper(
      width: double.infinity,
      height: 54,
      text: "检查更新",
      textSize: 16,
      textAlignment: Alignment.centerLeft,
      padding: EdgeInsets.only(left: 20, right: 20),
      child1: Image.asset(Comm.IMG_ARROW_RIGHT, width: 18, height: 18),
      child1Alignment: Alignment.centerRight,
      child1Margin: EdgeInsets.only(right: 20),
      child2: Offstage(
        offstage: null == newVersion,
        child: Text(
          "新版本：$newVersion",
          style: TextStyle(color: Colors.red),
        ),
      ),
      child2Alignment: Alignment.centerRight,
      child2Margin: EdgeInsets.only(right: 38),
      onClick: () {
        closeLoading = Toast.loading("检查更新...");
        _updateVersion(false);
      },
    );
  }

  ///分割线
  Widget _dividerWidget() {
    return Container(
      height: 1,
      width: MediaQuery.of(context).size.width,
      color: Color(0xffF2F2F2),
      margin: EdgeInsets.only(left: 20, right: 20),
    );
  }

  CancelFunc closeLoading;

  ///版本更新检查
  void _updateVersion(bool isFirst) {
    Http.get(Api.URL_PARAM_VERSION, successCallBack: (data) async {
      if (null != closeLoading) {
        closeLoading();
      }
      Map params = json.decode(data);
      if (params.containsKey("version")) {
        String version = params["version"];
        print("新版本：$version， 当前版本：${Comm.versionName}");
        if (version == Comm.versionName) {
          if (!isFirst) {
            Toast.show("已经是最新版本");
          }
          return;
        } else {
          setState(() {
            newVersion = version;
          });
        }
        var newVer = version.split(".");
        var oldVer = Comm.versionName.split(".");
        bool isUpdate = false;
        if (int.parse(newVer[0]) > int.parse(oldVer[0])) {
          isUpdate = true;
        } else if (int.parse(newVer[1]) > int.parse(oldVer[1])) {
          isUpdate = true;
        } else if (int.parse(newVer[2]) > int.parse(oldVer[2])) {
          isUpdate = true;
        }

        if (isUpdate && !isFirst) {
          String apkUrl = params["apkUrl"];
          if (!apkUrl.startsWith("http")) {
            apkUrl = Api.getUrl(apkUrl);
          }
          LogUtil.v("下载地址：$apkUrl");
          List<String> contents = List();
          contents.add("发布时间:${params["versionTime"]}");
          contents.add("更新信息：");
          contents.addAll(params["versionInfo"].toString().split("\\n"));
          AppUpgrade.appUpgrade(
            context,
            Future.value(
              AppUpgradeInfo(
                title: "新版本$version",
                contents: contents,
                force: false,
                apkDownloadUrl: apkUrl,
              ),
            ),
          );
        }
      }
    }, errorCallBack: (data) {
      Toast.show(data);
      if (null != closeLoading) {
        closeLoading();
      }
    });
  }
}
